package com.coffee.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 模拟post表单请求
     *
     * @param http_url   请求地址
     * @param parameters 请求参数
     * @return 结果
     */
    @SuppressWarnings("all")
    public static String doPostNew(String http_url, Map<String, String> parameters) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            if (parameters != null) {
                for (Map.Entry<String, String> e : parameters.entrySet()) {
                    method.addParameter(e.getKey(), e.getValue());
                }
            }
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
    }


    /**
     * 模拟post表单请求
     *
     * @param http_url   请求地址
     * @param parameters 请求参数
     * @return 结果
     */
    public static String doPost(String http_url, Map<String, String> parameters) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            if (parameters != null) {
                for (Map.Entry<String, String> e : parameters.entrySet()) {
                    method.addParameter(e.getKey(), e.getValue());
                }
            }
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("dopost fail:param" + parameters, e);
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }


    public static String get(String url, Map<String, String> params) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;
        StringBuilder str = new StringBuilder();
        str.append(url);

        if (params != null) {
            boolean first = true;
            for (String key : params.keySet()) {
                if (first) {
                    first = false;
                    str.append("?");
                } else {
                    str.append("&");
                }
                str.append(key).append("=").append(params.get(key));
            }
        }
        //System.err.println(str.toString());
        HttpGet get = new HttpGet(str.toString());
        body = invoke(httpclient, get);

        httpclient.getConnectionManager().shutdown();

        return body;
    }

    public static String doPostWithUtf8(String http_url, Map<String, String> parameters) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            // 添加参数
            if (parameters != null) {
                for (Map.Entry<String, String> e : parameters.entrySet()) {
                    method.addParameter(e.getKey(), e.getValue());
                }
            }
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("dopost fail:param" + parameters, e);
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 模拟post表单请求
     *
     * @param http_url   请求地址
     * @param parameters 请求参数
     * @return 结果
     */
    public static String doPostByTimeLimit(String http_url, Map<String, String> parameters,
                                           Integer timeout) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            if (parameters != null) {
                for (Map.Entry<String, String> e : parameters.entrySet()) {
                    method.addParameter(e.getKey(), e.getValue());
                }
            }
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("dopost fail:param" + parameters, e);
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 模拟post表单请求
     *
     * @param http_url   请求地址
     * @param parameters 请求参数
     * @return 结果
     */
    public static String doPostByCharset(String http_url, Map<String, String> parameters,
                                         String charset) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            if (parameters != null) {
                for (Map.Entry<String, String> e : parameters.entrySet()) {
                    method.addParameter(e.getKey(), e.getValue());
                }
            }
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("dopost fail:param" + parameters, e);
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 模拟post xml 请求
     *
     * @param http_url 请求地址
     * @param xml      请求xml内容
     * @return 结果
     */
    public static String doXmlPost(String http_url, String xml) {
        PostMethod method = null;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            method.setRequestEntity(new StringRequestEntity(xml));
            method.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
            client.executeMethod(method);
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    public static String postBody(String url, String params) {
        try {
            HttpPost httpost = new HttpPost(url);
            httpost.setEntity(new StringEntity(params, "UTF-8"));
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpost);
            String ret = EntityUtils.toString(response.getEntity(), "utf-8");
            return ret;
        } catch (IOException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1);
        }
    }

    /**
     * @param http_url 请求地址
     * @return get请求结果
     */
    public static String doGet(String http_url) {
        HttpMethod method;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration hcfg = new HostConfiguration();
            hcfg.setHost(uri);
            client.setHostConfiguration(hcfg);
            // 参数验证
            client.getParams().setAuthenticationPreemptive(true);
            // GET请求方式
            method = new GetMethod(http_url);
            client.executeMethod(method);
            return method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("HttPClientUtil.doGet fail ", e);
            throw new RuntimeException(e);
        }
    }

    public static String get(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;
        StringBuilder str = new StringBuilder();
        str.append(url);
        HttpGet get = new HttpGet(str.toString());
        body = invoke(httpclient, get);

        httpclient.getConnectionManager().shutdown();

        return body;
    }

    private static String paseResponse(HttpResponse response) {
        HttpEntity entity = response.getEntity();

        String charset = EntityUtils.getContentCharSet(entity);

        String body = null;
        try {
            body = EntityUtils.toString(entity, "UTF-8");
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body;
    }

    private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) {

        HttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response);

        return body;
    }

    private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {
        HttpResponse response = null;

        try {
            httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT,
                    "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * @param http_url       请求地址
     * @param json JSON字符串
     * @return
     */
    public static String doPostJson(String http_url, String json) {
        PostMethod method = null;
        String result = "";
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration cf = new HostConfiguration();
            cf.setHost(uri);
            client.setHostConfiguration(cf);
            client.getParams().setAuthenticationPreemptive(true);
            method = new PostMethod(http_url);
            // 添加参数
            method.setRequestEntity(new StringRequestEntity(json));
            method.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            client.executeMethod(method);
            method.getParams().setContentCharset("UTF-8");
            // 打印服务器返回的状态
            logger.debug("【" + http_url + "请求结果状态】" + method.getStatusLine());
            // 输出返回的信息
            result = method.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return result;
    }

    /**
     * @param http_url 请求地址
     * @return get请求结果
     * @throws IOException
     */
    public static InputStream doGetInputStream(String http_url) {
        HttpMethod method;
        try {
            URI uri = new URI(http_url, true);
            HttpClient client = new HttpClient();
            HostConfiguration hcfg = new HostConfiguration();
            hcfg.setHost(uri);
            client.setHostConfiguration(hcfg);
            // 参数验证
            client.getParams().setAuthenticationPreemptive(true);
            // GET请求方式
            method = new GetMethod(http_url);
            client.executeMethod(method);
            return method.getResponseBodyAsStream();
        } catch (IOException e) {
            logger.error("HttPClientUtil.doGet fail ", e);
            throw new RuntimeException(e);
        }
    }

    public static JSONObject getCarrier5th(String mobile) throws IOException {
        int i = 0;
        JSONObject object = null;
        while (i < 5) {
            object = getCarrier(mobile);
            i++;
            if (object != null) {
                break;
            }
        }
        return object;
    }

    public static JSONObject getCarrier(String mobile) {
        String jsonString = doGet(
                "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobile);
        jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "");
        //logger.info("mobile:" + mobile + ",json:" + jsonString);
        JSONObject object = null;
        try {

            object = JSON.parseObject(jsonString);
        } catch (Exception e) {
            logger.error("HttPClientUtil.getCarrier fail ", e);
        }

        return object;
    }

    public static final String sendHttpsRequestByPost(String url, Map<String, String> params) {
        String responseContent = null;
        org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
        //创建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        //这个好像是HOST验证
        X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

            @Override
            public void verify(String arg0, SSLSocket arg1) throws IOException {
            }

            @Override
            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
            }

            @Override
            public void verify(String arg0, X509Certificate arg1) throws SSLException {
            }
        };
        try {
            //TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("TLS");
            //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[]{xtm}, null);
            //创建SSLSocketFactory
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            socketFactory.setHostnameVerifier(hostnameVerifier);
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity(); // 获取响应实体
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 1000; i++) {
            System.out.println("次数:" + (i + 1) + "|" + getCarrier5th("18368083711"));
        }
		/*InputStream in = doGetInputStream(
			"http://wx.qlogo.cn/mmopen/aYMa9zpdAC04TWY6GtSHibZ9Qficgnbm7O6pib7nHHBuh8jnKT2ZcymMIZu4tlbGMJia2BDbEicrtybyG5Y4guDzfxV8A2wQTZr55/0");
		String dest = UUIDUtil.getUUID() + ".jpg";
		//String path=PropertiesHelp.getProperty("IMG_SERVER_THUMB_PATH");
		String filename = "d:/" + dest;
		File file = new File(filename);
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		in.close();*/

    }

}
